function [o_status, o_message] = mkadir(varargin)
% mkadir  - create an absolute directory (unlike to MATLAB's mkdir)
%
% FORMAT:         mkadir <dirname> [-p]
%
%    dirname      string absolute directory to create
%    -p           when given, try to create parent dir(s) first
%
% the usage is straight forward...
%
% mkadir c:\temp\this
% mkadir c:\temp\this\is\just\a\test -p
%
% st = mkadir(['/tmp/' temppath '/.log');
%
% See also mkdir.

% Version:  v0.5c
% Build:    6120415
% Date:     Dec-04 2006, 3:15 PM CET
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% enough arguments ?
if nargin < 1
    error( ...
        'BVQXtools:TooFewArguments',...
        'Too few arguments. Try ''help %s''.',...
        mfilename ...
    );
end

% sanity checks
for acount = 1:nargin
    if ~ischar(varargin{acount})
        error( ...
            'BVQXtools:BadArgument',...
            'All arguments must be of type char.' ...
        );
    end
end

% extract parent for MATLAB's mkdir and check if mkadir will work
dirname = varargin{1};
if dirname(end) == filesep
    dirname(end) = [];
end

% get parts
[parent, name, ext] = fileparts(dirname);

% if parent does not yet exist
if exist(parent,'dir') ~= 7

    % only if -p argument is given
    if nargin > 1 && ...
        ischar(varargin{2}) && ...
        numel(varargin{2}) == 2 && ...
        all(lower(varargin{2}(:)') == '-p')

        % call recursively
        status = mkadir(parent,'-p');

        % status check
        if status < 1
            error( ...
                'BVQXtools:DirNotCreated',...
                'Couldn''t create dir ''%s''.',...
                strrep(parent,'\','\\') ...
            );
        end

    % otherwise
    else

        % give error
        error( ...
            'BVQXtools:FolderNotExists',...
            'Parent folder ''%s'' doesn''t exist. Try ''%s <DIR> -p''.',...
            strrep(parent,'\','\\'),...
            mfilename ...
        );
    end
end

% reassemble wanted filename
if ~isempty(ext)
    name = [name ext];
end

% let MATLAB to the rest
[status, message] = mkdir(parent, name);

% handle return values correctly
if status < 1
    error( ...
        'BVQXtools:DirNotCreated',...
        'Couldn''t create ''%s'' in ''%s''.',...
        name,...
        strrep(parent,'\','\\') ...
    );
end

% handle output
if nargout > 0
    o_status  = status;
end
if nargout > 1
    o_message = message;
end
